#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复1688搜索框显示异常的脚本
"""

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

def fix_search_box_display():
    """修复搜索框显示问题"""
    
    print("=== 1688搜索框显示问题诊断与修复 ===")
    
    # 设置浏览器选项
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    # 设置中文语言环境
    options.add_argument('--lang=zh-CN')
    options.add_argument('--accept-lang=zh-CN,zh,en-US,en')
    
    driver = webdriver.Chrome(options=options)
    
    try:
        print("\n1. 访问1688首页...")
        driver.get("https://www.1688.com")
        time.sleep(3)
        
        # 清除可能的缓存和cookies
        print("2. 清除浏览器缓存和cookies...")
        driver.delete_all_cookies()
        driver.execute_script("window.localStorage.clear();")
        driver.execute_script("window.sessionStorage.clear();")
        
        # 刷新页面
        driver.refresh()
        time.sleep(3)
        
        # 查找搜索框
        search_selectors = [
            "input[name='keywords']",
            "input[placeholder*='搜索']",
            ".search-input",
            "#search-input",
            "[class*='search'] input"
        ]
        
        search_box = None
        for selector in search_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                if elements:
                    search_box = elements[0]
                    print(f"3. 找到搜索框: {selector}")
                    break
            except:
                continue
        
        if search_box:
            print("\n4. 检查搜索框当前状态...")
            current_value = search_box.get_attribute('value')
            placeholder = search_box.get_attribute('placeholder')
            print(f"   当前值: '{current_value}'")
            print(f"   占位符: '{placeholder}'")
            
            # 如果搜索框有异常内容，清除它
            if current_value and current_value != "数据线":
                print("\n5. 检测到搜索框异常内容，正在清除...")
                search_box.clear()
                time.sleep(0.5)
                
                # 使用JavaScript强制清除
                driver.execute_script("arguments[0].value = '';", search_box)
                time.sleep(0.5)
                
                print("   已清除异常内容")
            
            print("\n6. 重新输入正确的关键词...")
            keyword = "数据线"
            
            # 方法1: 直接输入
            search_box.clear()
            time.sleep(0.5)
            search_box.send_keys(keyword)
            time.sleep(1)
            
            final_value = search_box.get_attribute('value')
            print(f"   输入后的值: '{final_value}'")
            
            if final_value == keyword:
                print("   ✅ 搜索框显示正常")
            else:
                print("   ❌ 搜索框仍有问题，尝试JavaScript方法...")
                
                # 方法2: 使用JavaScript
                driver.execute_script(f"""
                    var element = arguments[0];
                    element.value = '{keyword}';
                    element.dispatchEvent(new Event('input', {{ bubbles: true }}));
                    element.dispatchEvent(new Event('change', {{ bubbles: true }}));
                """, search_box)
                time.sleep(1)
                
                final_value = search_box.get_attribute('value')
                print(f"   JavaScript输入后的值: '{final_value}'")
                
                if final_value == keyword:
                    print("   ✅ JavaScript方法修复成功")
                else:
                    print("   ❌ 问题仍然存在，可能是网站端问题")
            
            print("\n7. 建议的解决方案:")
            print("   - 清除浏览器缓存和cookies")
            print("   - 使用无痕模式浏览")
            print("   - 检查浏览器语言设置")
            print("   - 尝试不同的浏览器")
            print("   - 如果是爬虫代码，使用JavaScript方法输入")
            
        else:
            print("❌ 未找到搜索框")
            
    except Exception as e:
        print(f"修复过程中出错: {e}")
        
    finally:
        input("\n按回车键关闭浏览器...")
        driver.quit()

if __name__ == "__main__":
    fix_search_box_display()